﻿package {
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	public class Loading extends MovieClip {
		private var dial:Sprite;
		private var percent:TextField;
		private var format:TextFormat;
		private var sect:Number = 12;
		private var color:Number = 0x777777;
		private var thickness:Number = 2;
		private var radius_inside:Number = 10;
		private var radius_outside:Number = 15;
		private var speed:Number = 1;
		private var degree:Number;
		private var loading:Sprite;
		private var rate:Number;
		public function Loading():void {
			stop();
			stage.align = "TL";
			stage.scaleMode = "noScale";
			//
			rate = stage.frameRate;
			stage.frameRate = 15;
			//
			format = new TextFormat();
			format.font = "Helvetica";
			format.color = color;
			format.size  = 10;
			//
			degree = 360 / sect;
			dial = drawDial();
			percent = new TextField();
			percent.autoSize = "left";
			percent.selectable = false;
			percent.defaultTextFormat = format;
			loading = new Sprite();
			loading.addChild(dial);
			loading.addChild(percent);
			addChild(loading);
			addEventListener(Event.ENTER_FRAME, r, false, 0, true);
			//
			root.loaderInfo.addEventListener(ProgressEvent.PROGRESS, p, false, 0, true);
			root.loaderInfo.addEventListener(Event.COMPLETE, c, false, 0, true);
		}
		//dial
		private function drawDial():Sprite {
			var sp:Sprite = new Sprite();
			with (sp.graphics) {
				var trans:Number = 1 / sect;
				var radian:Number = degree * Math.PI / 180;
				for (var i:uint = 0; i < sect; i ++) {
					lineStyle(thickness, color, i * trans);
					var cos:Number = Math.cos(i * radian);
					var sin:Number = Math.sin(i * radian);
					var x1:Number = radius_inside * cos;
					var y1:Number = radius_inside * sin;
					var x2:Number = radius_outside * cos;
					var y2:Number = radius_outside * sin;
					moveTo(x1, y1);
					lineTo(x2, y2)
				}
			}
			return sp;
		}
		//rotation
		private function r(e:Event):void {
			dial.rotation += degree * speed;
			percent.x = - percent.width * 0.5;
			percent.y = - percent.height * 0.5;
			loading.x = stage.stageWidth * 0.5;
			loading.y = stage.stageHeight * 0.5;
		}
		//progress
		private function p(e:ProgressEvent):void {
			var per:Number = Math.round(e.bytesLoaded / e.bytesTotal * 100);
			if (per < 100) {
				percent.text = per.toString();
			}
		}
		//complete
		private function c(e:Event):void {
			percent.text = "";
			//removeEventListener(Event.ENTER_FRAME, r);
			//removeChild(loading);
			stage.frameRate = rate;
			//play();
		}
	}
}